<?php

namespace app\index\controller;

use think\Controller;

/**
 * Class Lists
 * @package app\index\controller
 * 筛选页控制器
 */
class Lists extends Controller
{
	public function index(){
		//处理title
		$conf = ['title'=>'阿里巴巴1688.com -列表','css'=>'lists','js'=>'lists'];
		$this->assign('conf',$conf);
		$cid = input('param.cid');

		/**
		 * 1.处理面包屑
		 */
		//获取该自己和自己所有父级
		$fatherData = $this->getFather(db('category')->select(),$cid);
		//数组转换
		$fatherData = array_reverse($fatherData);

		/**
		 * 2.通过分类id找见所有的商品选中的商品属性
		 */
		//获取自己和自己子集的cid
		$cids = $this->getSon(db('category')->select(),$cid);
		$cids[] = $cid;
		//通过cids去找见所有的商品
		$gids = db('goods')->whereIn('cid',$cids)->column('gid');
		if ($gids){
			//找见对应的商品属性
			$goodsData = db('goods-attribute')
				->whereIn('gid',$gids)
				->group('gtvalue')
				->select();
			//将taid相同的数据放在一起
			$newArr = [];
			foreach ($goodsData as $k=>$v){
				$newArr[$v['taid']][] = $v;
			}
			//组一个新数组
			$newArr2 = [];
			foreach ($newArr as $k=>$v){
					$newArr2[] = [
						'name' => db('type-attribute')->where('taid', $k)->value('taname'),
						'value' => $v
					];
			}
		}
		if(empty($newArr2)){
			$this->error('该商品无分类');
		}
		return view('',compact('fatherData','newArr2'));
	}

	//获取该自己和自己所有父级
	public function getFather($data,$cid){
		static $temp = [];
		foreach ($data as $k=>$v){
			if($cid == $v['cid']){
				$temp[] = $v;
				$this->getFather($data,$v['pid']);
			}
		}
		return $temp;
	}

	//获取自己的子集id
	public function getSon($data,$cid){
		static $temp = [];
		foreach ($data as $k=>$v){
			if ($cid == $v['pid']){
				$temp[] = $v['cid'];
				$this->getSon($data,$v['cid']);
			}
		}
		return $temp;
	}
}
